package com.service.infoEntry.controller;

import com.service.config.annotation.Log;
import com.service.config.enums.BusinessType;
import com.service.config.enums.OperatorType;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.Result;
import com.service.config.utils.UserTokenManager;
import com.service.infoEntry.dto.ProgrammeInfoDto;
import com.service.infoEntry.dto.ProgrammeInfoDto2;
import com.service.infoEntry.dto.UserDto;
import com.service.infoEntry.entity.ContentOfUpdateInfo;
import com.service.infoEntry.service.ProgrammeService;
import com.service.infoEntry.vo.ProgrammeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

import static com.service.infoEntry.constant.Constant.*;

@CrossOrigin
@RestController()
@RequestMapping("/programme")
@Api(value = "项目相关接口")
public class ProgrammeController {
    @Resource
    RedisUtil redisUtil;
    @Resource
    private ProgrammeService programmeService;


    @ApiOperation(value = "附件上传")
    @RequestMapping(value =  "/uploadAccessory",method = RequestMethod.POST,headers = "Content-Type=multipart/form-data")
    @ResponseBody
    public Result uploadAccessory(@RequestParam(value = "files",required = false) MultipartFile[] files,
                                 @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                String accessoryUrls = programmeService.uploadAccessory(files);
                return Result.ok().setData(accessoryUrls);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "附件下载")
    @RequestMapping(value = "/downloadAccessory",method = RequestMethod.GET)
    @ResponseBody
    public void downloadAccessory(@RequestParam("accessoryName")String accessoryName,
                                  HttpServletResponse response,
                                  @RequestHeader(value = "cloud-Auth-Token",required = false) @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                programmeService.downloadAccessory(accessoryName, response);
            } else {
                return;
            }
        }
    }

    @ApiOperation(value = "附件查询")
    @RequestMapping(value = "/queryAccessory",method = RequestMethod.GET)
    @ResponseBody
    public Result queryAccessory(@RequestParam("programmeId")String programmeId,
                                  @RequestHeader(value = "cloud-Auth-Token",required = false) @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                List<Map<String,String>> accessoryList = programmeService.queryAccessory(programmeId);
                return Result.ok().setData(accessoryList);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "附件删除")
    @RequestMapping(value = "/deleteAccessory",method = RequestMethod.DELETE)
    @ResponseBody
    public Result deleteAccessory(@RequestParam("programmeId")String programmeId,
                                  @RequestParam("accessoryName")String accessoryName,
                                  @RequestHeader(value = "cloud-Auth-Token",required = false) @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                return programmeService.deleteAccessory(programmeId,accessoryName);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "立项")
    @RequestMapping(value = "/setUpProgramme",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Result setUpProgramme(@RequestBody ProgrammeInfoDto programmeInfoDto,
                                @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                return programmeService.setUpProgramme(programmeInfoDto,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "项目跟踪")
    @RequestMapping(value = "/updateProgrammeInfo",method = RequestMethod.POST)
    @ResponseBody
    public Result updateProgrammeInfo(@RequestBody ProgrammeInfoDto programmeInfoDto,
                                 @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                return programmeService.updateProgrammeInfo(programmeInfoDto,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "项目关闭")
    @RequestMapping(value = "/closeProgramme",method = RequestMethod.POST)
    @ResponseBody
    public Result closeProgramme(@RequestBody ProgrammeInfoDto programmeInfoDto,
                                      @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                return programmeService.closeProgramme(programmeInfoDto,userId);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     *
     * @param programmeNo 项目编号 'no'
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询某个团队下的某一个项目")
    @RequestMapping(value = "/queryProgrammeOfTeamById",method = RequestMethod.POST)
    @ResponseBody
    public Result queryProgrammeOfTeamById(@RequestParam("programmeNo") String programmeNo,
                                           @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                           @RequestParam(value = "teamId")String teamId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                ProgrammeVo programmeVo = programmeService.queryProgrammeOfTeamById(programmeNo,userId,teamId);
                return Result.ok().setData(programmeVo);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "查询项目")
    @RequestMapping(value = "/queryProgramme",method = RequestMethod.GET)
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result queryProgramme(@RequestParam("teamId") String teamId,
                                 @RequestParam(value = "status",required = false) Integer status,
                                 @RequestParam(value = "name",required = false) String name,
                                 @RequestParam(value = "programmeStatus",required = false) Integer programmeStatus,
                                 @RequestParam(value = "page",required = true) Integer page,
                                 @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                Map<String, Object> map = programmeService.queryProgramme(teamId, userId, name, status, programmeStatus, page);
                return Result.ok().setData(map);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }


    @ApiOperation(value = "导出项目清单")
    @RequestMapping(value ="/exportProgrammeList",method = RequestMethod.GET)
    @ResponseBody
    public Result exportProgrammeList(@RequestParam("teamId") String teamId,
            @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                return programmeService.exportProgrammeList(teamId,userId);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 查询当前团队中的所有项目
     * @param
     * @return
     */
    @RequestMapping(value =  "queryAllProgrammeInTeam",method = RequestMethod.GET,produces="application/json")
    @ApiOperation(value = "查询当前团队所有项目")
    @ResponseBody
    public Result queryAllProgrammeInTeam(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                          @RequestParam("teamId") String teamId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                List<ProgrammeVo> pros = programmeService.queryAllProgrammeInTeam(teamId,userId);
                return Result.ok().setData(pros);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "下载项目清单模板")
    @RequestMapping(value = "/downloadModelProgrammeList",method = RequestMethod.GET)
    @ResponseBody
    public void downloadModelProgrammeList(@RequestHeader(value = "cloud-Auth-Token",required = false) @ApiParam("token") String cloudAuthToken,
                                             HttpServletResponse response) throws Exception {
        programmeService.downloadModelProgrammeList(response);
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                programmeService.downloadModelProgrammeList(response);
            } else {
                return;
            }
        }
        return;
    }

    /**
     * 项目清单上传
     * @param file
     * @return ok
     * @throws Exception
     */
    @ApiOperation(value = "项目清单上传")
    @RequestMapping(value = "uploadProgrammeList", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadProgrammeList(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                      @RequestParam("file")  @ApiParam("文件")MultipartFile file,
                                      @RequestParam("teamId") String teamId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);
                return  programmeService.uploadProgrammeList(file,teamId,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    @ApiOperation(value = "删除项目/事务")
    @RequestMapping(value = "/deleteProgrammeOrTransaction",method = RequestMethod.POST)
    @ResponseBody
    public Result deleteProgrammeOrTransaction(@RequestParam("teamId")@ApiParam("团队id") String teamId,
                                  @RequestParam("no")@ApiParam("项目/事务编号")String no,
                                  @RequestParam("type")@ApiParam("删除对象的类型:1-项目;0-事务")String type,
                                  @RequestHeader(value = "cloud-Auth-Token",required = false) @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                UserDto userDto = JsonXMLUtils.json2obj(value, UserDto.class);

                return programmeService.deleteProgrammeOrTransaction(teamId,no,type,userDto);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 查询团队下已删除项目:自己的项目和所有公开的项目
     * @param
     * @return
     */
    @RequestMapping(value =  "queryDeletedProgramme",method = RequestMethod.GET,produces="application/json")
    @ApiOperation(value = "查询已删除项目/事务")
    @ResponseBody
    public Result queryDeletedProgramme(@RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken,
                                          @RequestParam("teamId") String teamId,
                                        @RequestParam("type") String type,
                                        @RequestParam("page") Integer page,
                                        @RequestParam(value = "name",required = false) String name) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                return Result.ok().setData(programmeService.queryDeletedProgrammeOrTransaction(teamId,userId,type,page,name));
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 查询项目更新进展记录
     * @param cloudAuthToken
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询项目更新进展记录")
    @RequestMapping(value ="/queryUpdateProcessOfProgramme",method = RequestMethod.GET)
    public Result queryUpdateProcess(@RequestParam(value = "teamId",required = false) String teamId,
                                     @RequestParam(value = "programmeNo",required = false)@ApiParam("项目编号") String programmeNo,
                                     @RequestHeader(value = "cloud-Auth-Token") @ApiParam("token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                List<ContentOfUpdateInfo> updateProcess = programmeService.queryUpdateProcess(teamId,userId,programmeNo);
                return Result.ok().setData(updateProcess);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }
}
